const fs = require('fs')
const axios = require('axios');

const inputfile = "data.txt"
const outputfile = "output.json"

let requestCount = 0; // 请求计数器
// 初始化JSON结构
let jsonResult = {};
// 异步遍历和翻译每一行
let lineMaxCount = 0;
let lineCount = 0;

var lines = fs.readFileSync('translate.json', 'utf-8');
lines = JSON.parse(lines)

// 延迟函数
function delay(duration) {
    return new Promise(resolve => setTimeout(resolve, duration));
}

async function translate_baidu(text) {
    var data = {
        from: "en",
        to: "zh",
        q: text.replace(/_/g, ' ')
    }

    var config = {
        method: 'post',
        url: 'https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=24.8c0a3bba3cfc19edf32c31d3aa15fdb1.2592000.1707327005.282335-46686141',
        data: data
    }

    let translatedText = '';

    await axios(config)
        .then((response) => {
            if (response.data && response.data.result && response.data.result.trans_result.length != 0) {
                translatedText = response.data.result.trans_result[0].dst;
            }
        })
        .catch((err) => {
            console.log(err);
        });

    if (requestCount % 10 === 0) {
        await delay(2000);
    }

    return translatedText;
}

// 查询函数
function findEnvironmentInChinese(englishName) {
    // 检查提供的英文名称是否存在于数据对象中
    if (lines.hasOwnProperty(englishName)) {
        return lines[englishName];
    } else {
        return null;
    }
}

async function translateAndCombine(text) {
    const words = text.split('.');
    const translatedWords = [];

    for (const word of words) {
        var translatedWord = null
        if (findEnvironmentInChinese(word) == null) {
            translatedWord = await translate_baidu(word)
        } else {
            translatedWord = findEnvironmentInChinese(word);
        }
        translatedWords.push(translatedWord);
    }

    const combinedTranslation = translatedWords.join('.');

    jsonResult[text] = {
        translate: combinedTranslation,
        key: text
    };

    console.clear()
    console.log(`
------------------------------------------------------------------------
                | ${inputfile} 整理并翻译到 ${outputfile} 中 |
------------------------------------------------------------------------
  | ${text} => ${combinedTranslation} | ${lineCount}/${lineMaxCount} |
------------------------------------------------------------------------
    `);

    return combinedTranslation;
}

fs.readFile(inputfile, 'utf8', async (err, data) => {
    if (err) {
        console.error('Error reading the text file: ', err);
        return;
    }
    // 将数据按行分割
    const lines = data.split('\r\n');
    lineMaxCount = lines.length - 1

    await delay(50);
    for (const line of lines) {
        await translateAndCombine(line)

        if (++lineCount === lines.length) {
            fs.writeFile(outputfile, JSON.stringify(jsonResult), async (err) => {
                if (err) {
                    console.clear();
                    console.log(`
------------------------------------------------------------------------
    | ${inputfile} 写入${outputfile}错误: ${err} |
------------------------------------------------------------------------
    `);
                    await delay(2000);
                    console.clear()
                } else {
                    console.clear()
                    console.log(`
------------------------------------------------------------------------
        | ${inputfile} 已整理与翻译内容后，写入${outputfile}中 |
------------------------------------------------------------------------
    `);
                    await delay(2000);
                    console.clear()
                }
            });
        }
    }
});
